//
//  HLRefreshControl.swift
//  weibo1
//
//  Created by changhongliang on 2017/8/1.
//  Copyright © 2017年 richinfo. All rights reserved.
//

import UIKit
import SnapKit


class HLRefreshControl: UIRefreshControl {
  
    
    override init() {
        super.init()
        //添加布局子控件
       self.tintColor = UIColor.clear
       addSubview(refreshView)
        //2.布局子控件
        refreshView.snp.makeConstraints { (make) in
            make.center.equalTo(self)
            make.size.equalTo(CGSize(width: 150, height: 60))
        }
        
        //3.注册监听
       addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.new, context: nil)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.endAnimation()
        loadingFlag = false
    }
    
    //记录是否需要旋转
    var showTipFlag = false
    //记录是否需要执行菊花动画
    var loadingFlag = false
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //下拉刷新控件的frame一旦改变就会调用
        //规律是往下拉y值越小,往上推y值越大
        
        //1.过滤垃圾数值
        if frame.origin.y == 0 || frame.origin.y == -64 {
            return
        }
        //2.检查是否已经触发下拉刷新
        if isRefreshing && !loadingFlag {
            loadingFlag = true
            //开始执行动画
            refreshView.startAnimation()
            refreshView.refreshLabel?.text = "加载中..."
            return
        }

        
        //3.控制箭头
        if frame.origin.y < -50 && !showTipFlag {
            showTipFlag = true
            refreshView.refreshLabel?.text = "释放更新"
            refreshView.rotationArrow(flag: showTipFlag)
        }else if frame.origin.y > -50 && showTipFlag
        {
            showTipFlag = false
            refreshView.refreshLabel?.text = "下拉刷新"
            refreshView.rotationArrow(flag:showTipFlag)
        }
        
    
    }
    
   // MARK: - 懒加载
    private lazy var refreshView = HLRefreshView(frame: CGRect.zero)
}


class HLRefreshView: UIView {
    //箭头视图
    var refreshImageView: UIImageView?
    //右侧文字label
    var refreshLabel: UILabel?
    //菊花视图
    var loadingView:UIView?
    
    override init(frame: CGRect){
        super.init(frame: frame)
        
        //添加下拉label
        refreshLabel = UILabel(title: "下拉刷新")
        refreshLabel?.font = UIFont.systemFont(ofSize: 13)
        refreshLabel?.tintColor = UIColor.lightGray
        addSubview(refreshLabel!)
        refreshLabel?.snp.makeConstraints { (make) in
            make.centerX.equalTo(self).offset(25)
            make.bottom.equalTo(self).offset(-20)
        }
        
        //添加下拉的imageview
        refreshImageView = UIImageView(image: UIImage(named:"tableview_pull_refresh"))
        addSubview(refreshImageView!)
        refreshImageView?.snp.makeConstraints { (make) in
            make.centerX.equalTo(self).offset(-25)
            make.centerY.equalTo(refreshLabel!)
        }
        refreshImageView?.sizeToFit()
        
       //添加菊花视图
        loadingView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        addSubview(loadingView!)
        loadingView?.snp.makeConstraints({ (make) in
            make.centerX.equalTo(self).offset(-25)
            make.centerY.equalTo(refreshLabel!)
        })
        

        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func rotationArrow(flag: Bool)
    {
        //设置控件显示隐藏
        loadingView?.isHidden = true
        refreshImageView?.isHidden = false
        /*
         规律: 1.默认是顺时针 2.就近原则
         */
        var angle = CGFloat.pi
        angle = flag ? angle + 0.01 : angle - 0.01
        UIView.animate(withDuration: 0.1) { () -> Void in
            self.refreshImageView!.transform = self.refreshImageView!.transform.rotated(by: angle)
        }
    }
    
    
    // MARK: - 内部控制方法
    /// 开始菊花旋转动画
     fileprivate func startAnimation()
    {
        // 0.隐藏提示视图
        loadingView?.isHidden = false
        refreshImageView?.isHidden = true
        // 1.创建动画对象
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        
        // 2.设置动画属性
        anim.toValue = 2 * CGFloat.pi
        anim.duration = 10.0
        anim.repeatCount = MAXFLOAT
        
        // 3.将动画添加到图层
        loadingView!.layer.add(anim, forKey: nil)
    }
    
    /// 停止菊花旋转动画
    fileprivate func endAnimation()
    {
        // 0.显示提示视图
        loadingView?.isHidden = true
        refreshImageView?.isHidden = false
        // 1.移除动画
        loadingView!.layer.removeAllAnimations()
    }


    
}
